package com.my.download;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * 文件下载
 *
 * @author Lelezhang
 * @create 2020-07-17 22:50
 */
public class DownloadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取下载的文件名
        String downloadFileName = "/1.jpg";
        // 去读要下载文件的内容
        ServletContext servletContext = request.getServletContext();
        String mimeType = servletContext.getMimeType("/1.jpg");
        // 设置响应头告诉客户端响应类型
        response.setContentType(mimeType);
        // 设置成附件可下载
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("李智恩.jpg", "UTF-8"));
        // 获取该文件的流并拷贝流
        InputStream resourceAsStream = servletContext.getResourceAsStream(downloadFileName);
        IOUtils.copy(resourceAsStream, response.getOutputStream());
    }
}
